package com.example.myapplication

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import com.example.android_program.data_class.movie_info
import com.example.myapplication.ui.movie.Cinema_ChooseTimeSlot
import com.example.myapplication.ui.movie.Date_info
import kotlinx.android.synthetic.main.activity_pay.*
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import java.lang.StringBuilder
import java.lang.reflect.Field
import java.net.URLEncoder
import kotlin.concurrent.thread

class PayActivity : AppCompatActivity() {
    var ticket_num :Int = 0
    var ticket_price :Double = 0.0
    private var builderForCustom: CustomDialog.Builder? = null
    private var mDialog: CustomDialog? = null
    var pay = false
    val sever_ip = "192.168.43.8"

    val addOrderInfo_jsp = "http://${sever_ip}:8080/JspForAndroid/addOrderInfo.jsp"
    val searchMovieInfo_jsp = "http://${sever_ip}:8080/JspForAndroid/searchMovieInfo.jsp"
//    val addOrderInfo_jsp = "http://${resources.getString(R.string.sever_ip)}:8080/JspForAndroid/addOrderInfo.jsp"
//    val searchMovieInfo_jsp = "http://${resources.getString(R.string.sever_ip)}:8080/JspForAndroid/searchMovieInfo.jsp"
    var movie_name = ""
    var date = ""
    var language = ""
    var cinema_name = ""
    var start_time = ""
    var hall = ""
    var sum = 0.0
    var movie_src = ""
    var seat = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_pay)

        builderForCustom = CustomDialog.Builder(this)

        ticket_num = intent.getIntExtra("ticket_num", 0)
        ticket_price = intent.getDoubleExtra("ticket_price", 0.0)
        movie_name = intent.getStringExtra("movie_name").toString()
        date = intent.getStringExtra("date").toString()
        language = intent.getStringExtra("language").toString()
        cinema_name = intent.getStringExtra("cinema_name").toString()
        start_time = intent.getStringExtra("start_time").toString()
        hall = intent.getStringExtra("hall").toString()
        seat = intent.getStringExtra("seat").toString()
        //初始化
        pay_Number.text = ticket_num.toString()
        sum = ticket_num * ticket_price
        pay_money.text = sum.toString()
        pay_movieName.text = movie_name
        pay_movieKind.text = language
        pay_movieDate.text = date
        pay_movieTime.text = start_time
        pay_movieHall.text = hall
        pay_movieCinema.text = cinema_name
        pay_Seat.text = seat

        getAllTrainInfoJson2()

        pay_back.setOnClickListener {
            val intent = Intent(this, BuyTicketActivity::class.java)
            setResult(4, intent)
            finish()
        }

        pay_buttom.setOnClickListener{
            showTwoButtonDialog("", "这是自定义弹出框","确定", "取消", View.OnClickListener {
                // 操作
                Log.d("tyy","click yes")
                pay = true
                getAllTrainInfoJson()
                mDialog!!.dismiss()
            },View.OnClickListener {
                // 操作
                Log.d("tyy","click no")
                mDialog!!.dismiss()
            })

//            if (pay == true){
//
//            }
        }

    }
    private fun showSingleButtonDialog(title: String, alertText: String, btnText: String, onClickListener:View.OnClickListener) {
        mDialog = builderForCustom!!.setTitle(title)
            .setMessage(alertText)
            .setSingleButton(btnText, onClickListener)
            .createSingleButtonDialog()
        mDialog!!.show()
    }

    private fun showTwoButtonDialog(title: String, alertText: String, confirmText: String, cancelText: String, conFirmListener: View.OnClickListener, cancelListener: View.OnClickListener) {
        mDialog = builderForCustom!!.setTitle(title)
            .setMessage(alertText)
            .setPositiveButton(confirmText, conFirmListener)
            .setNegativeButton(cancelText, cancelListener)
            .createTwoButtonDialog()
        mDialog!!.show()
    }

    private fun getAllTrainInfoJson(){
        thread {
            try {
                val client = OkHttpClient()

                val requestBody = FormBody.Builder()
                    .add("cinema_name", URLEncoder.encode(cinema_name,"UTF-8"))
                    .add("movie_name", URLEncoder.encode(movie_name,"UTF-8"))
                    .add("movie_src", getResourceIdByString(movie_src).toString()) //暂时没传
                    .add("date", URLEncoder.encode(date,"UTF-8"))
                    .add("time", start_time)
                    .add("language", URLEncoder.encode(language,"UTF-8"))
                    .add("seat", URLEncoder.encode(seat,"UTF-8"))//暂时没传
                    .add("ticket_number", ticket_num.toString())
                    .add("price", sum.toString())
                    .build()

                //构建请求
                val request = Request.Builder()
                    .url(addOrderInfo_jsp)
                    .post(requestBody)
                    .build()
                //执行
                client.newCall(request).execute()

            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }

    private fun getAllTrainInfoJson2(){
        thread {
            try {
                val client = OkHttpClient()

                val requestBody = FormBody.Builder()
                    .add("movie_Name", URLEncoder.encode(movie_name,"UTF-8"))
                    //.add("endStation", "衢州")
                    .build()

                //构建请求
                val request = Request.Builder()
                    .url(searchMovieInfo_jsp)
                    .post(requestBody)
                    .build()
                //执行
                val response= client.newCall(request).execute()
                //得到返回值
                val responseData = response.body?.string()
                val result = parseJson2(responseData)
                if (responseData != null){
                    runOnUiThread{
                        //txtData.text = result
                        //更新布局
                        pay_movieSrc.setImageResource(getResourceIdByString(movie_src))
                    }
                }
            }catch (e: java.lang.Exception){
                e.printStackTrace()
            }
        }
    }

    private fun parseJson2(jsonData:String?):String{
        val builder = StringBuilder()

        try {
            //json数组
            val jsonArray = JSONArray(jsonData)
            for (i in 0 until jsonArray.length()){
                //取出元素
                val jsonObject = jsonArray.getJSONObject(i)
                movie_src = jsonObject.getString("movie_src")

               // builder.append("$movie_src--$movie_name--$movie_type--$movie_time--$movie_test--$movie_acter, ")

//                Looper.prepare()
//                Toast.makeText(this, builder.toString(), Toast.LENGTH_LONG).show()
//                Looper.loop()
            }
        }catch (e: java.lang.Exception){
            e.printStackTrace()
        }

        return builder.toString()
    }

    private fun getResourceIdByString(s: String?): Int {
        try {
            val field: Field = R.drawable::class.java.getField(s)
            return field[null].toString().toInt()
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return 0
    }
}